package com.rjj.wlqq.listen.interceptor;

import com.rjj.wlqq.tool.console.ConsoleTool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 任建军
 * @Title: 方法拦截器
 * @date 2019/1/8 17:37
 * @Description: 测试拦截一个方法
 * @URL:
 */
public class MethodInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(MethodInterceptor.class);

    /**
     * true和false表示可不可以通过
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("---------------------开始进入请求地址拦截----------------------------");
        if(handler instanceof HandlerMethod) {
            HandlerMethod handler1 = (HandlerMethod) handler;
            //pathTest
            String signatureName = handler1.getMethod().getName();
            Class<?> declaringClass = handler1.getMethod().getDeclaringClass();
            // com.rjj.wlqq.index.IndexController
            String name = declaringClass.getName();
            // IndexController
            String simpleName = declaringClass.getSimpleName();
            // /pathTest
            String servletPath = request.getServletPath();
            // get|post
            String requestMethod = request.getMethod();

            ConsoleTool.Console(request,signatureName,name,requestMethod,servletPath,simpleName);
        }
        return true;
    }

    /**
     * 该方法将在Controller执行之后，返回视图之前执行，modelAndView表示请求Controller处理之后返回的Model和View对象，所以可以在
     * 这个方法中修改modelAndView的属性，从而达到改变返回的模型和视图的效果。
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("---------------视图渲染之后的操作-------------------------");
    }
}
